package com.yuntsg.nnsfcp.util.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class WosHttpClient {

    public static void createFile(String path, byte[] content) throws IOException {

        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

    public String getHtmlWithProxy(CookieStore cookieStore, String url) {
        System.out.println("httpclient里面的地址" + url);
        String html = "";
        //CredentialsProvider credsProvider =LoadInfo.build();// new BasicCredentialsProvider();
        //	credsProvider.setCredentials(new AuthScope("58.194.172.216",10086), (Credentials) new UsernamePasswordCredentials("qf", "qf3.1415"));

        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore)
                    //.setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httpget = new HttpGet(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigure();//RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).setProxy(new HttpHost("58.194.172.216",10086))
//.build();//设置请求和传输超时时间
                httpget.setConfig(requestConfig);
                httpget.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.9 Safari/537.36");
                httpget.addHeader(HttpHeaders.REFERER, "http://apps.webofknowledge.com");
                responce = httpClient.execute(httpget);//得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();//返回码
                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {//200正常  其他就不对
                    HttpEntity entity = responce.getEntity();   //获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace("&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public String postHtmlWithProxy(CookieStore cookieStore, String url, Map<String, String> map) {
        System.out.println("httpclient里面的地址" + url);
        String html = "";
        //CredentialsProvider credsProvider = LoadInfo.build();//new BasicCredentialsProvider();
        //	credsProvider.setCredentials(new AuthScope("58.194.172.216",10086), (Credentials) new UsernamePasswordCredentials("qf", "qf3.1415"));

        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore)
                    //.setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {

                httppost = new HttpPost(url);
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                if (map != null) {
                    for (Entry<String, String> entry : map.entrySet()) {
                        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }

                httppost.setEntity(new UrlEncodedFormEntity(nvps, "utf8"));
                RequestConfig requestConfig = LoadInfo.buildRequestConfigure();//设置请求和传输超时时间
                httppost.setConfig(requestConfig);
                httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.9 Safari/537.36");
                httppost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                httppost.addHeader("Accept-Language", "en-US,zh-CN;q=0.8,zh;q=0.5,en;q=0.3");
                httppost.addHeader(HttpHeaders.REFERER, "http://apps.webofknowledge.com");
                responce = httpClient.execute(httppost);//得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();//返回码
                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1));
                if (resStatu == 301 || resStatu == 302) {
                    URL reurl = new URL(new URL(url), responce.getFirstHeader("location").getValue());
                    HttpGet httpget = new HttpGet(reurl.toString());
                    httpget.setConfig(requestConfig);
                    httpget.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.9 Safari/537.36");
                    httpget.addHeader(HttpHeaders.REFERER, "http://apps.webofknowledge.com");
                    httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    httpget.addHeader("Accept-Language", "en-US,zh-CN;q=0.8,zh;q=0.5,en;q=0.3");
                    responce = httpClient.execute(httpget);//得到responce对象
                }

                System.out.println();
                //if (resStatu==HttpStatus.SC_OK) {//200正常  其他就不对
                HttpEntity entity = responce.getEntity();   //获得相应实体
                if (entity != null) {
                    html = EntityUtils.toString(entity, "UTF-8");
                    //html = html +"<lasturl>"+lasturl+"</lasturl>";
                    //createFile("d:/sss.html",html.getBytes());
                    break;
                }

                //}
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }
}
